/**
 *
 * @param {string} path 接口路径
 * @param {object} params 参数，如果是上传文件，请传FormData类型
 * @param {object} options
 */
export function request(
    url,
    params = {},
    { method = "POST", timeout = 15 * 1000, onProgress } = {}
  ) {
    const formatResponse = (response) => {
      return {
        ok: response.code === "000000" || response.code === "00000000", // 成功的错误码
        code: response.code,
        msg: response.msg,
        data: response.data,
      };
    };
    return new Promise((resolve, reject) => {
      let body = null;
      if (params instanceof FormData) {
        // 上传文件
        body = params;
      } else {
        if (method === "GET") {
          let queryString = objectToQuerystring(params);
          url += (url.indexOf("?") === -1 ? "?" : "&") + queryString;
        } else {
          // POST参数格式化,一般就下面两种:form和json
          //body = objectToQuerystring(params) // form
          body = JSON.stringify(params); // json
        }
      }
  
      let xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.responseType = "json";
      xhr.timeout = timeout;
      // xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8')
      if (params.headerContentType) {
        xhr.setRequestHeader("Content-type", params.headerContentType);
      }else{
        xhr.setRequestHeader("Content-type", "application/json");
      }
      xhr.onload = () => {
        let res;
  
        if (xhr.status !== 200) {
          if (xhr.status >= 500 && xhr.status < 600) {
            res = {
              msg: "服务正忙，请稍后再试",
              code: -1,
              ok: false,
            };
          } else if (xhr.status === 404) {
            res = {
              msg: "接口不存在(" + xhr.status + ")",
              code: -1,
              ok: false,
            };
          } else {
            res = {
              msg: "请求异常(" + xhr.status + ")",
              code: -1,
              ok: false,
            };
          }
        } else {
          if (!(xhr.response instanceof Object)) {
            res = {
              msg: "解析结果JSON失败",
              code: -1,
              ok: false,
            };
          } else {
            res = formatResponse(xhr.response);
          }
        }
  
        resolve(res);
      };
      xhr.onerror = (e) => {
        let res = {
          msg: "网络异常，请稍后再试",
          code: -1,
          ok: false,
        };
        resolve(res);
      };
      xhr.ontimeout = (e) => {
        let res = {
          msg: "请求超时，请稍后再试",
          code: -1,
          ok: false,
        };
        resolve(res);
      };
      if (onProgress) {
        xhr.onprogress = (e) => {
          onProgress(e);
        };
      }
      xhr.send(body);
    });
  }
  